package core

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"testGin/model/mysql"
	"testGin/model/tool"
	"time"
)

type Cuser struct {
	token      string
	expireTime int
}

type res struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func (c Cuser) Login(cs *gin.Context,account string, password string) res {

	admin, err := mysql.Admins{}.GetAdminByAccount(account)
	if err != nil {
		return res{0, "账户不存在"}
	}
	if admin.Status != 1 {
		return res{0, "该账户被冻结"}
	}

	var pwd string = tool.GetPass(password, admin.Acode)

	if admin.Password != pwd {
		return res{0, "密码错误"}
	}
	c.loginSuccess(cs,admin)

	return res{1, "登录成功"}
}

func (s Cuser) CheckLogin(cs *gin.Context,token string) bool {
	var flag bool
	aonline, err := mysql.Aonline{}.GetAdminByToken(token)

	if err != nil {
		flag = false
	}else{
        flag = true
		//过期
		if aonline.ExpireTime < int32(time.Now().Unix()) {
            flag = false
			delToken(cs)
		}
	}
	return flag
}

func (s Cuser) LoginOut(c *gin.Context,token string) {
	mysql.Aonline{}.Del(token)
	delToken(c)
}

func (c Cuser) loginSuccess(gc *gin.Context,admin mysql.Admins) {

	now := time.Now()

	loginKey := getLoginKey(admin.Account)

	addData := fmt.Sprintf("当前时间为： %d%02d%d", now.Year(), now.Month(), now.Day())

	addDataInt,_ := strconv.Atoi(addData)

	aonlines := mysql.Aonline{
		IdAdmin:    admin.Id,
		Ip:         "127.0.0.1",
		LoginKey:   loginKey,
		ActiveTime: int32(now.Unix()),
		ExpireTime: int32(now.Unix() + 3600),
		AddTime:    int32(time.Now().Unix()),
		Address:    "本机",
		AddDate:    addDataInt,
	}
	mysql.Aonline{}.DelById(admin.Id)
	mysql.Aonline{}.Add(aonlines)

    tool.SessionSet(gc,"token",loginKey)
    tool.SessionSet(gc,"admin",admin)
}


func (c Cuser) GetAdminNodes(adminId uint) map[string]interface{}{

	roleId := mysql.AdminRole{}.GetRidByAdmin(adminId)

	nodes := mysql.AdminNodeItem{}.GetNodesByRoleId(roleId)

	dd := mysql.Node{}.GetNodesByIds(nodes)

	nodelist := mysql.Node{}.BuildMenuChild(0,dd)

	item := mysql.AdminInfo{}.GetItem()


	var homeInfo map[string]interface{} = map[string]interface{}{
		"title":"信息面板",
		"href": "/system/index/console",
	}

	var logoInfo map[string]interface{}  = map[string]interface{}{
		"title":item.Sitename,
		"href": "/system/index/index",
		"image": item.Logo,
	}

	var nodeMaps map[string]interface{} = map[string]interface{}{
		"homeInfo":  make(map[string]interface{}),
		"logoInfo":  make(map[string]interface{}),
		"menuInfo":  make([]mysql.Node,0),
	}
	nodeMaps["homeInfo"] = homeInfo
	nodeMaps["logoInfo"] = logoInfo
	nodeMaps["menuInfo"] = nodelist
	return nodeMaps
}

func getLoginKey(str string) string {
	return tool.Md5Str(str + string(time.Now().Unix()))
}

func delToken(c * gin.Context){
	tool.SessionDel(c,"token")
	tool.SessionDel(c,"admin")
}